package com.sichemxiang.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mysql.cj.log.Log;
import com.sichemxiang.config.exception.BaseException;
import com.sichemxiang.config.exception.ErrorEnum;
import com.sichemxiang.entity.AnswerResultDto;
import com.sichemxiang.entity.ChatMessageDto;
import com.sichemxiang.service.AnswerService;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Optional;

/**
 * @Author: xsz
 * @DateTime: 2025/1/14 0:20
 **/

@Service
public class AnswerServiceImpl implements AnswerService {

    @Value("${chat.api.url}")
    private String aPiUrl;

    @Value("${chat.api.token}")
    private String apiToken;


    @Override
    public AnswerResultDto answer(ChatMessageDto chatMessageDto) {
        if (!StringUtils.hasText(chatMessageDto.getChatMessage())) {
            throw new BaseException(ErrorEnum.RESULT_NULL,"问题不能为空");
        }

        // 存储最终的回答结果
        String res = "";

        AnswerResultDto answerResultDto = new AnswerResultDto();

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 创建 HttpPost 请求，指定 API 地址
        HttpPost post = new HttpPost(aPiUrl);
        // 添加请求头
        post.addHeader("Authorization", "Bearer " + apiToken);
        post.addHeader("Content-Type", "application/json");
        // 构建请求体 JSON 字符串，将 question 作为 user 的 content 参数
        String paramJson = "{\n" +
                "    \"model\": \"ep-20250113170521-8skvb\",\n" +
                "    \"messages\": [\n" +
                "        {\n" +
                "            \"role\": \"system\",\n" +
                "            \"content\": \"You are a helpful assistant.\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"role\": \"user\",\n" +
                "            \"content\": \"" + chatMessageDto.getChatMessage() + "\"\n" +
                "        }\n" +
                "    ]\n" +
                "  }";
        // 将 JSON 字符串作为请求体实体
        StringEntity stringEntity = new StringEntity(paramJson, ContentType.create("text/json", "UTF-8"));
        post.setEntity(stringEntity);
        // 执行请求
        try {
            CloseableHttpResponse response = httpClient.execute(post);
            // 获取响应状态码
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                // 提取响应内容
                res = extractContentFromJson(EntityUtils.toString(response.getEntity()));
                answerResultDto.setAnswer(res);
            } else {
                System.out.println("Request failed with status code: " + statusCode);
            }
            // 关闭资源
            response.close();
            httpClient.close();
        }catch (IOException e) {
            e.printStackTrace();
        }

        return answerResultDto;
    }

    /**
     * 解析json
     * @param jsonString
     * @return
     */
    private static String extractContentFromJson(String jsonString) {
        try {
            JSONObject jsonObject = JSON.parseObject(jsonString);
            JSONArray choices = jsonObject.getJSONArray("choices");
            if (choices.size() > 0) {
                JSONObject choice = choices.getJSONObject(0);
                JSONObject message = choice.getJSONObject("message");
                return message.getString("content");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


}
